<!-- 设备 -->

<template>
  <FormSlot :label="`${GETTER.type}范围`" bind="planAssetIds" :tip="`请选择${GETTER.type}范围`" required>
    <div>
      <span v-for="item in numDict" :key="item[0]" class="el-button--text" @click="toOpen(item[0])">
        <span>{{ item[1] }}({{ item[2] }})</span>
      </span>

      <span v-if="!isShow">
        <BtnText v-if="numDict.length" title="清除" @click="toClear" />
        <BtnPrimary v-else title="选择" @click="toOpen(one.planBizType === 1 ? one.applyObjectId : '')" />
      </span>
    </div>

    <EasyModal v-model="easyVisible" :title="`选择${GETTER.type}范围`" large @submit="toSubmit">
      <ChooseDevice :obj="obj" bind="planAssetDto" :assetTypeId="assetTypeId" />
    </EasyModal>
  </FormSlot>
</template>

<script>
// ============================== 导入依赖 ============================== //

import CORE from '@/CORE'

// ============================== 导出组件 ============================== //

export default {
  /**
   * 名称定义 (实际使用名称)
   */
  name: 'MyDevice',

  /**
   * 混入列表 (配置选项合并)
   */
  mixins: [CORE.mixWeb()],

  /**
   * 状态数据 (函数返回对象)
   */
  data() {
    return {
      easyVisible: false, // 弹窗是否可见
      assetTypeId: '', // 默认资产分类
      obj: { planAssetDto: [] }, // 数据对象
    }
  },

  /**
   * 计算属性 (慎用箭头函数)
   */
  computed: {
    /**
     * 数量字典
     */
    numDict() {
      const { planAssetDto } = this.one
      const numDict = []
      planAssetDto.forEach((item) => {
        const index = numDict.findIndex((dict) => dict[0] === item.assetTypeId)
        if (index >= 0) numDict[index][2]++
        else numDict.push([item.assetTypeId, item.assetTypeName, 1])
      })
      return numDict
    },
  },

  /**
   * 监听属性 (深度 deep 首次 immediate)
   */
  watch: {
    /**
     * 监听弹窗可见
     */
    easyVisible: {
      immediate: true,
      handler(visible) {
        visible && this.toReset()
      },
    },
  },

  /**
   * 本地方法 (轻量重要在前)
   */
  methods: {
    /**
     * 弹窗
     */
    toOpen(id) {
      this.assetTypeId = id || ''
      this.easyVisible = true
    },

    /**
     * 提交
     */
    toSubmit() {
      this.one.planAssetDto = CORE.clone(this.obj.planAssetDto)
      this.one.planAssetIds = this.one.planAssetDto.map((item) => item.id).join()
      this.easyVisible = false
    },

    /**
     * 重置
     */
    toReset() {
      this.obj = { planAssetDto: CORE.clone(this.one.planAssetDto) }
    },

    /**
     * 清除
     */
    toClear() {
      this.assetTypeId = ''
      this.one.planAssetDto = []
      this.one.planAssetIds = ''
      this.obj = { planAssetDto: [] }
    },
  },
}
</script>
